package esb.chapter11.scubadiving.servicemix;

import javax.annotation.Resource;
import javax.jbi.messaging.DeliveryChannel;
import javax.jbi.messaging.ExchangeStatus;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.MessagingException;
import javax.jbi.messaging.NormalizedMessage;
import javax.xml.transform.Source;

import org.apache.log4j.Logger;
import org.apache.servicemix.MessageExchangeListener;
import org.apache.servicemix.components.util.ComponentSupport;

import esb.chapter11.scubadiving.bean.DivingAgencyIF;
import esb.chapter11.scubadiving.model.DivingBooking;
import esb.chapter11.scubadiving.model.DivingRequest;
import esb.util.framework.JiBXUtil;

public class DivingAgencyService extends ComponentSupport implements MessageExchangeListener {
	
	private final static Logger logger = Logger.getLogger(DivingAgencyService.class);
	@Resource
	private DeliveryChannel channel;
	private DivingAgencyIF divingAgency;
	
    public void onMessageExchange(MessageExchange exchange) throws MessagingException {
    	if (exchange.getStatus() != ExchangeStatus.ACTIVE) {
    		logger.info("state is not active so ignoring call");
    		return;
    	}
    	DivingRequest divingRequest = null;
    	try {
    		Source contentSource = getInMessage(exchange).getContent();
    		divingRequest = (DivingRequest) JiBXUtil.unmarshalDocument(
    				contentSource, DivingRequest.class);
        } catch(Exception e) {
        	logger.error("error while reading payload", e);
        }
        DivingBooking divingBooking = divingAgency.processBooking(divingRequest);
        NormalizedMessage outMessage = exchange.createMessage();
    	try {
    		outMessage.setContent(JiBXUtil.marshalDocument(divingBooking, "UTF-8"));
    	} catch(Exception e) {
    		logger.error("error setting diving booking message", e);
    	}
        exchange.setMessage(outMessage, "out");
        channel.send(exchange);
    }

	public void setDivingAgency(DivingAgencyIF divingAgency) {
		this.divingAgency = divingAgency;
	}
}
